package com.thread.sychronized;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author wangyingjie
 * @date
 * @remark 账户
 */
public class Account {
    private final ReentrantLock lock = new ReentrantLock();
    /**
     * 账户编号
     */
    private String accountNo;

    /**
     * 余额
     */
    private double balance;

    /**
     * 是否有存款
     */
    private boolean flag;

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    public String getAccountNo() {
        return accountNo;
    }

    public void setAccountNo(String accountNo) {
        this.accountNo = accountNo;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    /**
     * 根据钱包编号判断是否同一个钱包
     *
     * @param obj
     * @return
     */
    @Override
    public boolean equals(Object obj) {
        if (obj.getClass() != Account.class)
            return false;
        Account account = (Account) obj;
        return accountNo.equals(account.getAccountNo());
    }

    /**
     * 同步方法取钱
     * @param money
     */
    public synchronized void draw(double money) throws InterruptedException {
        if (flag){//有钱
            if (balance != 0 && balance >= money) {
                System.out.println("取出【" + money + "】现金");
                balance -= money;
                System.out.println("剩余【" + balance + "】现金");
                flag=false;
                this.notifyAll();
            } else {
                System.out.println("账户余额不足");
            }
        }else {//没钱等待
            System.out.println("没钱不允许取，线程阻塞...");
            this.wait();
        }
    }

    /**
     * 存钱
     * @param money
     * @throws InterruptedException
     */
    public synchronized void deposit(double money) throws InterruptedException {
        if (!flag){//没钱
            if (balance == 0 && money > 0) {
                System.out.println("存入【" + money + "】现金");
                balance += money;
                System.out.println("剩余【" + balance + "】现金");
                flag=true;
                this.notifyAll();
            } else {
                System.out.println("账户余额不足");
            }
        }else {//没钱等待
            System.out.println("有钱不允许存，线程阻塞...");
            this.wait();
        }
    }
}
